package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.entity.Boy;
import cn.chinaflame.pagodas.enums.ResultEnum;
import cn.chinaflame.pagodas.exception.BoyException;
import cn.chinaflame.pagodas.repository.BoyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class BoyService {
    @Autowired
    private BoyRepository boyRepository;

    /**
     * 数据库事物操作，只有查询的时候不用加
     * 比如同时插入两条数据如果一条失败事物就返回
     */
    @Transactional
    public void insertTwo() {
        Boy boyA = new Boy();
        boyA.setAge(18);
        boyA.setCupSize("A");
        boyRepository.save(boyA);

        Boy boyB = new Boy();
        boyB.setAge(19);
        boyB.setCupSize("B");
        boyRepository.save(boyB);
    }

    public void getAge(Integer id) throws Exception {
        Boy boy = boyRepository.findOne(id);
        Integer age = boy.getAge();
        if (age < 10) {
            throw new BoyException(ResultEnum.PRIMARY_SCHOOL);
        }
        if (age > 10 && age < 16) {
            throw new BoyException(ResultEnum.MIDDLE_SCHOOL);
        }
    }

    /**
     * 单元测试
     * 通过ID插叙一个男生的信息
     *
     * @param id
     * @return
     */
    public Boy findOne(Integer id) {
        return boyRepository.findOne(id);
    }
}















